import React, { PropTypes, Component } from 'react'
import fetch from 'isomorphic-fetch'
import { Link } from 'react-router'

import Table from './Table'
import NavLink from './NavLink'
import style from './PointM.css'
import {myAjaxJson,ROOTURL} from './../publicAPI/publicAPI'

class PointM extends Component {

    constructor(props, context) {
        super(props, context)
        console.log("初始化")
        this.state = {
            delete: false,
            deleteId: -1,
            PointMdata:[],
          
        };// 初始化状态
         this.start=0;
        this.page=1;
        this.getlist.bind(this);
        
    }
 
    componentWillMount() {
  
     this.getlist("","");
    }

    componentDidMount() {
        console.log("安装成功")
     
    }
    getlist(dname,phone){
        
         let _this=this
        let params={
              "where":{},
            
              "order":
                [           // ORDER BY  
                    ["id", "asc"],    // id ASC,
         
                ],

                 "start":0, 
                 "limit":10
             
            
         
        }
        if(dname!=""){
        params={
           "where":
                {"customer":{
                    "dname":[
                        ["eq",dname]
                    ],
                  }
                },
            "order":
                [           // ORDER BY  
                    ["id", "asc"],    // id ASC,
         
                ],
                "limit":10
             
         }
        }
        else if(phone!=""){
            params={
            "where":
                {"customer":{
                    "phone":[
                        ["eq",phone]
                    ],
                  }
                },
            "order":
                [           // ORDER BY  
                    ["id", "asc"],    // id ASC,
         
                ],
                "limit":10
             
            }
        }

        else if(phone!=""&&dname!=""){
            params={
             "where":{
                "customer":{
                    "phone":[
                        ["eq",phone]
                    ],
                },
                "dname":
                [
                    ["eq",dname]
                ],
                
              },
               "order":
                [           // ORDER BY  
                    ["id", "asc"],    // id ASC,
         
                ],
                "limit":10
            }
        }    
        this.HandleInfoById(params);
         
       
        
    }

    HandleInfoById(params){//获取钱包用户普通信息

        let _this=this;
        fetch(ROOTURL+'credit/account/search.api',{
                method: 'post',
                headers: {
                    "Content-type": "application/json; charset=UTF-8"
                },
        
                body:JSON.stringify(params)
        }).then(response=>{return response.json()})
        .then(data=>_this.handlePhoneById(data)

        )

    }
     handlePhoneById(AccountInfo){//通过id获取用户手机号,AccountInfo为用户的普通信息数组
           let IdArray=[];
           let phoneArray=[];
           AccountInfo.map(function(elem, index) {
                 IdArray.push(elem.id);
           });
         //console.log(AccountInfo);
           let params={
              "where":{
                "id":
                [
                    ["in",IdArray]
                ],
                
              },
               "order":
                [           // ORDER BY  
                    ["id", "asc"],    // id ASC,
         
                ],
                "limit":10

           }
           fetch(ROOTURL+'customer/profile/search.api',{
                method: 'post',
                headers: {
                    "Content-type": "application/json; charset=UTF-8"
                },
        
                body:JSON.stringify(params)
        }).then(response=>{return response.json()})
        .then(
            data=>{ data.map(function(elem, index) {
                     AccountInfo[index].phone=elem.phone;
                     AccountInfo[index].openid=elem.openid;
                     AccountInfo[index].dname=elem.dname;
                     //console.log(AccountInfo[index]);
                    });
                    this.setState({
                        PointMdata:AccountInfo
                    })
                    
                  }
            )




    }
    
    handleDelete(id){
        this.setState({
            delete: !this.state.delete,
            deleteId : id
        })
    }

      handlePageClick(e) { //1为下一页，2为上一页
        let _buttonValue = e.target.value;
        let next=document.getElementsByClassName("next")[0];
        let prev=document.getElementsByClassName("prev")[0];
        let _this=this;
      
       
        if (_buttonValue == 1) {
          
          this.start=this.start+9;
          this.page++;
          prev.style.display="block";

        } else {
          this.start=this.start-9;
          this.page--;
          next.style.display="block";
        }
        console.log(this.page);
        let params={
             "order":
            [           // ORDER BY  
                    ["id", "DESC"],    // id ASC,
         
            ],
            "start":this.start,//
            "limit":10

        }
        if(this.page==1){
       
            prev.style.display="none";
        }
        if(this.start>=0){//如果当前页页码是负数则不请求数据
          
           fetch(ROOTURL+'credit/account/search.api',{
                method: 'post',
                headers: {
                    "Content-type": "application/json; charset=UTF-8"
                },
        
                body:JSON.stringify(params)
            }).then(response=>{return response.json()})
             .then(data=>{
                     console.log("legth:"+data.length);
                     if(data.length<10&&this.page!=1)
                    next.style.display="none";
                    this.handlePhoneById(data);
             })   
         //console.log("StatePage:"+_this.state.page);
          //console.log("StatetobeEnd:"+_this.state.toBeEnd);
        }

    }

    handlepoint(){
            let dname=this.refs.openid.value;
            let phone=this.refs.phone.value;
            this.getlist(dname,phone);
    }

    tHead() {
        var data = [
            {name: "顾客名称"},
            {name: "微信号"},
            {name: "电话"},
            {name: "积分"},
            {name: "备注"},
            {name: "操作"}
        ];
        const _headArr = [];
        const _width = {
            "0": "15%",
            "1": "18%",
            "2": "16%",
            "3": "20%",
            "4": "20%",
            "4": "20%"
        };
        //_headArr.push(<th style={{width:'5%'}} role="1" key='' onClick={(e) => this.handleSelect(e)}></th>)
        _headArr.push(data.map((item, index) => <th style={{width: _width[index]}} role="1"
                                                    key={index}>{item.name}</th>));
        return _headArr;
    }

    tBody() {
        var array=new Array();
        var _this=this;
        var i;
        console.log(_this.state.PointMdata)
        var _data=_this.state.PointMdata;
   
      return _data.map((item) => <tr key = {item.id} >

                     
                     < td > { item.dname } < /td > 
                      < td > { item.openid } < /td > 
                     < td > { item.phone } < /td>
                      < td > { item.value } < /td >  
                     < td > { item.remark } < /td >
                     <td>
                        <span><NavLink to={`/PointM/${item.id}`} className="rbtn green">查看</NavLink></span>
                     </td>
        </tr>)
  
    }

    render() {
        console.log("理发师管理" + "渲染" + this.state.page)
        return (
            <div className="right-wapper">
            <div className="rt-wrap rt-wrap-header">
                    <div className="input-div pr">
                        <label>顾客名称：</label>
                        <input type="text" placeholder="请输入要查找的顾客名称：" className="default-text"
                            ref="openid"value={this.state.InputValue}/>
                    </div>
                    <div className="input-div">
                        <label>电话号码：</label>
                        <input type="text" placeholder="请输入要查找的电话号码" className="default-text"
                            ref="phone"value={this.state.InputValue}/>
                    </div>
                    <div className="input-div">
                        <button className="search-btn" onClick={(e) => this.handlepoint(e)}>查找</button>
                    </div>
                    
                </div>
               <div className="rt-wrap">
                    <h3 className="catagory">
                        <span className="cata-title">积分管理</span>
                        <button className="next" value="1" onClick={(e) => this.handlePageClick(e)}></button>
                        <button style={{display:'none'}} className="prev" value="2" onClick={(e) => this.handlePageClick(e)}></button>
                    </h3>
                    <Table tHead={this.tHead.bind(this)()} tBody={this.tBody.bind(this)()}/>
                </div>
                { this.state.delete ?
                    <div id={style["msgDialog"]}>
                        <div className={style["msgDialog_div"]}><h3 id={style["msgDialog_title"]}>删除提示？</h3><p id={style["msgDialog_content"]}>
                            确认删除？</p>
                            <div className={style["msgDialog_button"]}>
                                <button id={style["msgDialog_yes"]}>确定</button>
                                <button id={style["msgDialog_no"]}
                                        onClick={()=>this.setState({delete: !this.state.delete})}>
                                    取消
                                </button>
                            </div>
                        </div>
                    </div> : null}
            </div>

        )
    }
}

export default PointM
